#import "CountTimer.h"

@interface CountTimer()
@property (nonatomic, assign) NSInteger timePassed;
@property (nonatomic, assign) BOOL isTimerRunning;

@end

@implementation CountTimer{
    dispatch_source_t _timer;
    TimerMode _mode;
    TimerUpdateBlock _updateBlock;
    TimerCompletionBlock _completionBlock;
    NSInteger _elapsedTime;
    NSInteger _originalDuration;

}

- (instancetype)initWithDuration:(NSInteger)duration
                           mode:(TimerMode)mode
                    updateBlock:(TimerUpdateBlock)updateBlock
                completionBlock:(TimerCompletionBlock)completionBlock {
    self = [super init];
    if (self) {
        _duration = duration;
        _mode = mode;
        _updateBlock = updateBlock;
        _completionBlock = completionBlock;
        _originalDuration = duration;
        _isTimerRunning = NO;
        _elapsedTime = 0;
    }
    return self;
}

-(void)setDuration:(NSInteger)duration{
    _duration = duration;
    _elapsedTime = duration;
}

-(BOOL)isTimerRunning{
    return _isTimerRunning;
}
  
- (void)dealloc {
    [self stop];
}
  
- (void)start {
    if (!_isTimerRunning) {
        _isTimerRunning = YES;
        _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
        dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0);
        dispatch_source_set_event_handler(_timer, ^{
            if (_mode == TimerModeCountdown) {
                _duration -= 1.0;
                if (_updateBlock) {
                    _updateBlock(_duration);
                }
                if (_duration <= 0) {
                    [self stop];
                    if (_completionBlock) {
                        _completionBlock();
                    }
                }
            } else if (_mode == TimerModeCountup) {
                _elapsedTime += 1.0;
                if (_updateBlock) {
                    _updateBlock(_elapsedTime);
                }
                // No natural completion for countup, so it will run indefinitely unless stopped
            }
        });
        dispatch_resume(_timer);
    }
}
  
- (void)stop {
    if (_isTimerRunning) {
        _isTimerRunning = NO;
        dispatch_source_cancel(_timer);
        _timer = NULL;
    }
}
  
- (void)reset {
    [self stop];
    if (_mode == TimerModeCountdown) {
        _duration = _originalDuration;
    } else if (_mode == TimerModeCountup) {
        _elapsedTime = 0; // Reset the elapsed time for countup mode
    }
}
  
@end
